﻿// (c) Comkarl Calipso
// By Matías Fidemraizer (http://www.matiasfidemraizer.com)
// -------------------------------------------------
// http://calipso.codeplex.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace Comkarl.Web.UI.Controls
{
    /// <summary>
    /// Represents the base class for any server control. It adds some utilities and unique features, like rendering control using an XML writer.
    /// </summary>
    public abstract class WebControl : CompositeControl
    {
        public WebControl()
        {
            Init += WebControl_Init;
        }

        /// <summary>
        /// Gets the page to which current control is child of.
        /// </summary>
        public Page CurrentPage
        {
            get
            {
                return ((Page)Page);
            }
        }

        /// <summary>
        /// In derived classes, gets the common unique identifier of this control,
        /// both in server and client side.
        /// </summary>
        internal protected virtual string CommonID
        {
            get
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// Gets a string resource by its key.
        /// </summary>
        /// <param name="key">
        /// The whole resource string key.
        /// </param>
        /// <returns></returns>
        protected string GetResourceString(string key)
        {
            return HttpContext.GetGlobalResourceObject(GetType().Name, key) as string;
        }

        /// <summary>
        /// In derived classes, performs initialization operations against child controls.
        /// </summary>
        protected virtual void InitControls()
        {
        }

        /// <summary>
        /// In derived classes, adds event handlers to current controls and/or child ones.
        /// </summary>
        protected virtual void AddEventHandlers()
        {
        }

        /// <summary>
        /// In derived classes, sets control's style, setting CSS classes to controls.
        /// </summary>
        protected virtual void SetControlStyle()
        {
        }

        public override sealed void RenderControl(HtmlTextWriter writer)
        {
            if (!Page.IsCallback)
            {
                using (MemoryStream textStream = new MemoryStream())
                using (XmlWriter doc = XmlWriter.Create(textStream, new XmlWriterSettings { CloseOutput = true, Encoding = Encoding.UTF8, ConformanceLevel = ConformanceLevel.Fragment }))
                {
                    RenderControl(doc);

                    doc.Flush();
                    textStream.Position = 0;

                    writer.Write(Encoding.UTF8.GetString(textStream.ToArray()));
                }
            }
        }

        /// <summary>
        /// In derived classes, renders arbitrary HTML using an XML writer.
        /// </summary>
        /// <param name="writer"></param>
        protected virtual void RenderControl(XmlWriter writer)
        {
            using (MemoryStream textStream = new MemoryStream())
            using (StreamWriter textWriter = new StreamWriter(textStream))
            using (HtmlTextWriter htmlWriter = new HtmlTextWriter(textWriter))
            {
                foreach (Control control in Controls)
                {
                    control.RenderControl(htmlWriter);
                }

                htmlWriter.Flush();
                textStream.Position = 0;

                writer.WriteRaw(Encoding.UTF8.GetString(textStream.ToArray()));
            }
        }

        private void WebControl_Init(object sender, System.EventArgs e)
        {
            InitControls();
            AddEventHandlers();
            SetControlStyle();
        }
    }
}